package com.lb.shopguide.adapter;

import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.lb.shopguide.R;
import com.netease.nim.uikit.business.recent.RecentContactsCallback;
import com.netease.nim.uikit.business.recent.RecentContactsFragment;
import com.netease.nim.uikit.business.session.emoji.MoonUtil;
import com.netease.nim.uikit.business.session.helper.TeamNotificationHelper;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.ui.drop.DropFake;
import com.netease.nim.uikit.common.ui.drop.DropManager;
import com.netease.nim.uikit.common.ui.imageview.HeadImageView;
import com.netease.nim.uikit.common.util.sys.ScreenUtil;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.netease.nim.uikit.impl.cache.TeamDataCache;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.attachment.NotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.model.Team;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kang on 2017/8/11.
 */

public class AdapterContact extends BaseQuickAdapter<RecentContact, BaseViewHolder> {
    private RecentContactsCallback callback;

    private int lastUnreadCount = 0;

    public AdapterContact(@LayoutRes int layoutResId, @Nullable List<RecentContact> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, final RecentContact item) {
        View view = helper.itemView;
        final FrameLayout portraitPanel = view.findViewById(R.id.portrait_panel);
        final DropFake tvUnread = view.findViewById(R.id.unread_number_tip);
        RelativeLayout layoutDelete = view.findViewById(R.id.delete_layout);
        LinearLayout layoutRoot = view.findViewById(R.id.layout_root);
        SwipeRevealLayout revealLayout = view.findViewById(R.id.swipe_reveal_layout);
        revealLayout.close(true);
        refresh(helper, item, helper.getAdapterPosition());
        tvUnread.setTouchListener(new DropFake.ITouchListener() {
            @Override
            public void onDown() {
                DropManager.getInstance().setCurrentId(item);
                DropManager.getInstance().down(tvUnread, tvUnread.getText());
            }

            @Override
            public void onMove(float curX, float curY) {
                DropManager.getInstance().move(curX, curY);
            }

            @Override
            public void onUp() {
                DropManager.getInstance().up();
            }
        });
        layoutDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnDeleteClickListener != null) {
                    mOnDeleteClickListener.onDeleteClick(item);
                }
            }
        });
        layoutRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mOnItemListener!=null){
                    mOnItemListener.onItem(item);
                }
            }
        });
    }

    public RecentContactsCallback getCallback() {
        return callback;
    }

    public void setCallback(RecentContactsCallback callback) {
        this.callback = callback;
    }

    public void refresh(BaseViewHolder helper, RecentContact recent, final int position) {
        final View view = helper.itemView;
        final ImageView imgUnreadExplosion = view.findViewById(R.id.unread_number_explosion);
        // unread count animation
        final boolean shouldBoom = lastUnreadCount > 0 && recent.getUnreadCount() == 0; // 未读数从N->0执行爆裂动画;
        lastUnreadCount = recent.getUnreadCount();

        updateBackground(helper, recent, position);

        loadPortrait(helper, recent);

        updateNickLabel(helper, UserInfoHelper.getUserTitleName(recent.getContactId(), recent.getSessionType()));

        updateOnlineState(helper, recent);

        updateMsgLabel(helper, recent);

        updateNewIndicator(helper, recent);

        if (shouldBoom) {
            Object o = DropManager.getInstance().getCurrentId();
            if (o instanceof String && o.equals("0")) {
                imgUnreadExplosion.setImageResource(com.netease.nim.uikit.R.drawable.nim_explosion);
                imgUnreadExplosion.setVisibility(View.VISIBLE);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ((AnimationDrawable) imgUnreadExplosion.getDrawable()).start();
                        // 解决部分手机动画无法播放的问题（例如华为荣耀）
                        notifyItemChanged(getHeaderLayoutCount() + position);
                    }
                });
            }
        } else {
            imgUnreadExplosion.setVisibility(View.GONE);
        }
    }

    private void updateBackground(BaseViewHolder helper, RecentContact recent, int position) {
        View view = helper.itemView;
        View bottomLine = view.findViewById(R.id.bottom_line);
        View topLine = view.findViewById(R.id.top_line);
        topLine.setVisibility(View.GONE);
        if (helper.getAdapterPosition() == mData.size() - 1) {
            bottomLine.setVisibility(View.GONE);
        } else {
            bottomLine.setVisibility(View.VISIBLE);
        }

        if ((recent.getTag() & RecentContactsFragment.RECENT_TAG_STICKY) == 0) {
            helper.getConvertView().setBackgroundResource(com.netease.nim.uikit.R.color.white);
        } else {
            helper.getConvertView().setBackgroundResource(com.netease.nim.uikit.R.drawable.nim_recent_contact_sticky_selecter);
        }
    }

    protected void loadPortrait(BaseViewHolder helper, RecentContact recent) {
        View view = helper.itemView;
        HeadImageView imgHead = view.findViewById(R.id.img_head);
        // 设置头像
        if (recent.getSessionType() == SessionTypeEnum.P2P) {
            imgHead.loadBuddyAvatar(recent.getContactId());
        } else if (recent.getSessionType() == SessionTypeEnum.Team) {
            Team team = TeamDataCache.getInstance().getTeamById(recent.getContactId());
            imgHead.loadTeamIconByTeam(team);
        }
    }

    private void updateNewIndicator(BaseViewHolder helper, RecentContact recent) {
        View view = helper.itemView;
        DropFake tvUnread = view.findViewById(R.id.unread_number_tip);
        int unreadNum = recent.getUnreadCount();
        tvUnread.setVisibility(unreadNum > 0 ? View.VISIBLE : View.GONE);
        tvUnread.setText(unreadCountShowRule(unreadNum));
    }

    private void updateMsgLabel(BaseViewHolder helper, RecentContact recent) {
        View view = helper.itemView;
        TextView tvMessage = view.findViewById(R.id.tv_message);
        TextView tvDatetime = view.findViewById(R.id.tv_date_time);
        ImageView imgMsgStatus = view.findViewById(R.id.img_msg_status);
        // 显示消息具体内容
        MoonUtil.identifyRecentVHFaceExpressionAndTags(mContext, tvMessage, getContent(recent), -1, 0.45f);
        MsgStatusEnum status = recent.getMsgStatus();
        switch (status) {
            case fail:
                imgMsgStatus.setImageResource(com.netease.nim.uikit.R.drawable.nim_g_ic_failed_small);
                imgMsgStatus.setVisibility(View.VISIBLE);
                break;
            case sending:
                imgMsgStatus.setImageResource(com.netease.nim.uikit.R.drawable.nim_recent_contact_ic_sending);
                imgMsgStatus.setVisibility(View.VISIBLE);
                break;
            default:
                imgMsgStatus.setVisibility(View.GONE);
                break;
        }

        String timeString = TimeUtil.getTimeShowString(recent.getTime(), true);
        tvDatetime.setText(timeString);
    }

    protected String getOnlineStateContent(RecentContact recent) {
        return "";
    }

    protected void updateOnlineState(BaseViewHolder helper, RecentContact recent) {
        View view = helper.itemView;
        TextView tvOnlineState = view.findViewById(R.id.tv_online_state);
        if (recent.getSessionType() == SessionTypeEnum.Team) {
            tvOnlineState.setVisibility(View.GONE);
        } else {
            tvOnlineState.setVisibility(View.VISIBLE);
            tvOnlineState.setText(getOnlineStateContent(recent));
        }
    }

    protected void updateNickLabel(BaseViewHolder helper, String nick) {
        View view = helper.itemView;
        TextView tvNickname = view.findViewById(R.id.tv_nickname);
        int labelWidth = ScreenUtil.screenWidth;
        labelWidth -= ScreenUtil.dip2px(50 + 70); // 减去固定的头像和时间宽度
        if (labelWidth > 0) {
            tvNickname.setMaxWidth(labelWidth);
        }
        tvNickname.setText(nick);
    }

    protected String unreadCountShowRule(int unread) {
        unread = Math.min(unread, 99);
        return String.valueOf(unread);
    }

    protected String getContent(RecentContact recent) {
        return descOfMsg(recent);
    }

    protected String descOfMsg(RecentContact recent) {
        if (recent.getMsgType() == MsgTypeEnum.text) {
            return recent.getContent();
        } else if (recent.getMsgType() == MsgTypeEnum.tip) {
            String digest = null;
            if (getCallback() != null) {
                digest = getCallback().getDigestOfTipMsg(recent);
            }

            if (digest == null) {
                digest = getDefaultDigest(null, recent);
            }

            return digest;
        } else if (recent.getAttachment() != null) {
            String digest = null;
            if (getCallback() != null) {
                digest = getCallback().getDigestOfAttachment(recent, recent.getAttachment());
            }

            if (digest == null) {
                digest = getDefaultDigest(recent.getAttachment(), recent);
            }

            return digest;
        }
        return "";
    }

    // SDK本身只记录原始数据，第三方APP可根据自己实际需求，在最近联系人列表上显示缩略消息
    // 以下为一些常见消息类型的示例。
    private String getDefaultDigest(MsgAttachment attachment, RecentContact recent) {
        switch (recent.getMsgType()) {
            case text:
                return recent.getContent();
            case image:
                return "[图片]";
            case video:
                return "[视频]";
            case audio:
                return "[语音消息]";
            case location:
                return "[位置]";
            case file:
                return "[文件]";
            case tip:
                List<String> uuids = new ArrayList<>();
                uuids.add(recent.getRecentMessageId());
                List<IMMessage> messages = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);
                if (messages != null && messages.size() > 0) {
                    return messages.get(0).getContent();
                }
                return "[通知提醒]";
            case notification:
                return TeamNotificationHelper.getTeamNotificationText(recent.getContactId(),
                        recent.getFromAccount(),
                        (NotificationAttachment) recent.getAttachment());
            default:
                return "[自定义消息] ";
        }
    }

    public interface OnDeleteClickListener {
        void onDeleteClick(RecentContact item);
    }

    private OnDeleteClickListener mOnDeleteClickListener;

    public void setOnDeleteClickListener(OnDeleteClickListener listener) {
        mOnDeleteClickListener = listener;
    }

    public interface OnItemListener {
        void onItem(RecentContact item);
    }

    private OnItemListener mOnItemListener;

    public void setOnItemListener(OnItemListener listener) {
        mOnItemListener = listener;
    }

}
